package com.jakeprim.util;

import com.jakeprim.demo.Column;
import com.jakeprim.demo.Order;
import com.jakeprim.demo.SqlState;

import java.lang.reflect.Field;

public class GenerateSqlUtil {
    public String query(Object obj) throws Exception {
        StringBuffer buffer = new StringBuffer();//拼接整体的查询SQL语句
        StringBuffer whereBuffer = new StringBuffer(" where "); //拼接查询条件SQL语句
        //select 字段 from 表名 where 条件
        buffer.append("select");
        //反射对象上的注解
        Class<?> objClass = obj.getClass();
        SqlState sqlState = objClass.getAnnotation(SqlState.class);//表名
        if (sqlState == null) {
            throw new RuntimeException("注解缺失");
        }
        String tableName = sqlState.value();
        Field[] fields = objClass.getDeclaredFields();//获取对象属性
        for (Field field : fields) {
            Column column = field.getAnnotation(Column.class);
            if (column == null) {
                continue;//不生成查询字段
            }
            if (column.value().equals("")) {//表字段名和属性名是一致的
                String name = field.getName();
                field.setAccessible(true);
                Object value = field.get(obj);
                buffer.append(" " + name + ",");
                if (value != null && Integer.parseInt(value.toString()) != 0) {
                    whereBuffer.append(" and " + name + "=" + value);
                }
            } else {
                String name = column.value();//表字段名和属性名不一致
                field.setAccessible(true);
                Object value = field.get(obj);
                buffer.append(" " + name + ",");
                if (value != null && Integer.parseInt(value.toString()) != 0) {
                    whereBuffer.append(" and " + name + "=" + value);
                }
            }
        }
        buffer.deleteCharAt(buffer.length() - 1);//删除最后一个逗号
        buffer.append(" from " + tableName);
        buffer.append(whereBuffer);
        return buffer.toString();
    }

    public static void main(String[] args) throws Exception {
        GenerateSqlUtil generateSqlUtil = new GenerateSqlUtil();
        Order order = new Order();
        order.setOrderNo("7789");
        String query = generateSqlUtil.query(order);
        System.out.println("query:" + query);

    }
}
